<template>
  <div>
    <el-upload
      :class="{ disabled: fileComputed }"
      :limit="1"
      action="#"
      list-type="picture-card"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
      :on-change="changefile"
      :before-upload="beforefile"
      :file-list="filelist"
      :http-request="upload"
    >
      <i class="el-icon-plus"></i>
    </el-upload>
  </div>
</template>

<script>
import { addphone } from "@/api/permission/users.js";
export default {
  name: "image",
  data() {
    return {
      filelist: [], //文件列表
      file: "", //照片地址,
      filename: "", //名字
      currentFileUid: null
      //  dialogVisible:false
    };
  },
  computed: {
    fileComputed() {
      return this.filelist.length === 1;
    }
  },
  methods: {
    //转base64

    //点击文件列表中已上传的文件时的钩子
    handlePictureCardPreview(file) {
      //   console.log(file);
    },
    //文件列表移除文件时的钩子
    handleRemove(file, fileList) {
      // console.log(file)
      this.filelist = this.filelist.filter(item => item.uid !== file.uid);
    },
    //当文件发生变化时的钩子不论成功失败都会出发
    async changefile(file, fileList) {
      // console.log(file, 111);
      // console.log(fileList, 222);
      this.filelist = fileList.map(item => item);
    },
    //上传文件之前的钩子
    beforefile(file) {
      // 要开始做文件上传的检查了
      // 文件类型 文件大小
      const types = ["image/jpeg", "image/gif", "image/bmp", "image/png"];
      if (!types.some(item => item === file.type)) {
        this.$message.error("上传图片只能是 JPG、GIF、BMP、PNG 格式!");
        return false;
      }
      //  检查大小
      const maxSize = 5 * 1024 * 1024;
      if (maxSize < file.size) {
        this.$message.error("图片大小最大不能超过5M");
        return false;
      }
      //   已经确定当前上传的就是当前的这个file了
      this.currentFileUid = file.uid; // 【新增】
      return true;
    },
    async upload(parmas) {
      //转成base64格式
      function getBase64(file) {
        return new Promise(function(resolve, reject) {
          let reader = new FileReader();
          let imgResult = "";
          reader.readAsDataURL(file);
          reader.onload = function() {
            imgResult = reader.result;
          };
          reader.onerror = function(error) {
            reject(error);
          };
          reader.onloadend = function() {
            resolve(imgResult);
          };
        });
      }
      this.filename = parmas.filename; //file名字
      const res = await getBase64(parmas.file);//赋值给请求字段
      const { data } = await addphone({
        file: res,
        filename: this.filename
      });
      this.$emit("sendOut", data.url);
    }
  }
};
</script>

<style scoped lang='scss'>
.disabled .el-upload--picture-card {
  display: none;
}
</style>